package com.cqndt.disaster.device.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cqndt.disaster.device.util.AjaxResult;
import org.springframework.validation.BindingResult;
import com.cqndt.disaster.device.util.Result;
import com.cqndt.disaster.device.util.ErrorInfo;
import com.cqndt.disaster.device.util.ErrorType;
import com.cqndt.disaster.device.util.ServiceException;
import org.springframework.context.support.DefaultMessageSourceResolvable;

/**
 * user: zhaojianji
 * date: 2017/05/25
 * desc:  公共controller类，所有的controller类都应该继承此类
 **/
@Slf4j
public class BaseController {
    /**
     * @param url 指定的url
     * @return spring 默认返回对应视图 重定向到指定url
     **/
    protected String redirect(String url) {
        return "redirect:" + url;
    }

    /**
     * @param url 指定的url
     * @return 返回视图 跳转到指定url
     **/
    protected String forward(String url) {
        return "forward:" + url;
    }

    /**
     * @return  断熔方法
     **/
    protected AjaxResult fallback(){
        AjaxResult result = new AjaxResult();
        result.setCode(405);
        result.setMsg("服务繁忙！");
        return result;
    }
    protected Result fallback_new(){
        Result result = new Result();
        result.setCode(405);
        result.setMsg("服务繁忙！");
        return result;
    }
    protected AjaxResult error(String error){
        AjaxResult result = new AjaxResult();
        result.setCode(300);
        result.setMsg(error);
        return result;
    }
    protected AjaxResult success(Object data,String success){
        AjaxResult result = new AjaxResult();
        result.setCode(200);
        result.setMsg(success);
        result.setData(data);
        return result;
    }

    /**
     * @param 从上下文中获取登录用户的信息
     * @return 返回用户信息
     **/
    /*protected UserDetail getUserDetail() {
    SecurityContextHolder.getContext().getAuthentication()
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        Object o = authentication.getPrincipal();

        if (o instanceof UserModel) {
            UserModel userDetails = (UserModel) o;
            log.Info("default-userDetails->" + userDetails);
            return userDetails.getUserDetail();
        }
        return null;
    }*/

    /**
     * @param 判断请求方是手机还是pc
     * @param request 请求
     * @return true 是手机访问 false 非手机访问
     **/

    protected boolean isMobile(HttpServletRequest request) {
        String userAgent = request.getHeader("user-Agent");
        String[] agent = {"Android", "iPhone", "Windows Phone", "MQQBrowser"};
        if (!userAgent.contains("Windows NT") || (userAgent.contains("Windows NT") && userAgent.contains("compatible; MSIE 9.0;"))) {
            // 排除 苹果桌面系统
            if (!userAgent.contains("Windows NT") && !userAgent.contains("Macintosh")) {
                for (String s : agent) {
                    if (userAgent.contains(s)) {
                        return true;
                    }
                }

            }
        }
        return false;
    }

    protected AjaxResult exceptionReslut(ServiceException e, HttpServletResponse response) {
        response.setStatus(e.getErrCode());
        return new AjaxResult(false, e.getErrCode(), e.getErrMsg());
    }

    protected AjaxResult commonResult(int result, String actionName) {
        AjaxResult ajaxResult = new AjaxResult();
        String msg = actionName;
        if (result > 0) {
            ajaxResult.setOk(true);
            ajaxResult.setCode(200);
            msg += "成功";
        } else {
            ajaxResult.setOk(false);
            ajaxResult.setCode(500);
            msg += "失败";
        }
        ajaxResult.setMsg(msg);
        return ajaxResult;
    }

    protected AjaxResult $entityResult(Object data, String msg,boolean b) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setOk(b);
        ajaxResult.setData(data);
        ajaxResult.setMsg(msg);
        return ajaxResult;
    }

    protected AjaxResult entityResult(Object data, String msg) {
        AjaxResult ajaxResult = new AjaxResult();
        if (data != null && data != (Object) 0) {
            ajaxResult.setOk(true);
            ajaxResult.setCode(200);
            ajaxResult.setData(data);
            msg += "成功";
        } else if (data == (Object) 0) {
            ajaxResult.setOk(false);
            ajaxResult.setCode(401);
            ajaxResult.setData(data);
            msg += "失败";
        } else {
            ajaxResult.setOk(false);
            ajaxResult.setData(null);
            if (msg.equals("用户名错误")){
                ajaxResult.setCode(617);
            }
            if (msg.equals("密码错误")){
                ajaxResult.setCode(618);
            }
            if (!msg.equals("用户名错误") && !msg.equals("密码错误")){
                ajaxResult.setCode(500);
                msg += "失败";
            }

        }
        ajaxResult.setMsg(msg);
        return ajaxResult;
    }


    protected AjaxResult pageResult(int curPage,int prePageSize,
    		int totalRecord,Collection<?> collection) {
        int totalPage;
        if (totalRecord % prePageSize == 0) {
            totalPage = totalRecord / prePageSize;
        } else {
            totalPage = totalRecord / prePageSize + 1;
        }
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setOk(true);
        ajaxResult.setCode(200);
        ajaxResult.setMsg("获取数据成功,数据条数:" + collection.size());
        ajaxResult.setCurPage(curPage);
        ajaxResult.setCurRecord(collection.size());
        ajaxResult.setTotalRecord(totalRecord);
        ajaxResult.setTotalPage(totalPage);
        ajaxResult.setPage(true);
        ajaxResult.setData(collection);
        ajaxResult.setPrePageSize(prePageSize);
        return ajaxResult;

    }


    protected AjaxResult bindErrorResult(BindingResult result) {
        List<ErrorInfo> errorInfos = new ArrayList<>();
        result.getAllErrors().forEach(error ->
            errorInfos.add(new ErrorInfo(((DefaultMessageSourceResolvable) error.getArguments()[0]).getCodes()[1], error.getDefaultMessage())));
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setOk(false);
        ajaxResult.setCode(ErrorType.DATA_BIND_ERROR.getCode());
        ajaxResult.setMsg(ErrorType.DATA_BIND_ERROR.getErrorMsg());
        ajaxResult.setErrors(errorInfos);
        log.error("返回错误结果:" + ajaxResult);
        return ajaxResult;
    }
    
}